﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;

using log4net;
using log4net.Config;

using Web.Library.DomainObject.SQLServer;
using Web.Library.DataAccess.SQLServer;

using Web.Support;

public partial class Control_Authentication : BaseUserControl
{
    //protected static readonly ILog log = LogManager.GetLogger(typeof(Global));
    protected void Page_Load(object sender, EventArgs e)
    {
        //log4net.Config.XmlConfigurator.Configure();
    }

    private ITemplate loginform = null;
    private ITemplate loginstatus = null;
    private ITemplate logintest = null;
    private ITemplate candidatestatus = null;
    [TemplateContainer(typeof(TemplateControl))]
    [PersistenceMode(PersistenceMode.InnerProperty)]
    [TemplateInstance(TemplateInstance.Single)]
    public ITemplate LoginForm
    {
        get { return loginform; }
        set { loginform = value; }

    }

    public ITemplate LoginStatus
    {
        get { return loginstatus; }
        set { loginstatus = value; }
    }

    public ITemplate LoginTest
    {
        get { return logintest; }
        set { logintest = value; }
    }

    public ITemplate CandidateStatus
    {
        get { return candidatestatus; }
        set { candidatestatus = value; }
    }

    public void Page_Init()
    {
        if (loginform != null && !Page.User.Identity.IsAuthenticated)
        {
            loginform.InstantiateIn(LoginFormPanel);
            LoginFormPanel.Visible = true;
        }

        if (loginstatus != null && Page.User.Identity.IsAuthenticated)
        {
            loginstatus.InstantiateIn(LoginStatusPanel);
            UserCurrent.Text = base.UserLoggedIn;// new AuthInfo().UserInfo().EmailAddress;
            LoginStatusPanel.Visible = true;
        }

        //if (logintest != null)
        //{
        //    logintest.InstantiateIn(LoginTestPanel);
        //    LoginTestPanel.Visible = true;
        //}

        //if (candidatestatus != null)
        //{
        //    candidatestatus.InstantiateIn(CandidateStatusPanel);
        //    CandidateStatusPanel.Visible = true;
        //}
    }

    //protected void LoginBtn_Click(object sender, EventArgs e)
    //{
    //    string email = Email.Value;
    //    string password = PassWord.Value;

    //    Profile profileDomain = new Profile();
    //    ProfileFacade profileFacade = new ProfileFacade();
    //    string message = string.Empty;

    //    try
    //    {
    //        profileDomain = profileFacade.getAuthenticationUser(email, password);
    //        if (profileDomain.ID == 0)
    //        {
    //            message = "Incorrect username or password!";
    //            this.SignOutMethod();
    //        }
    //        else
    //        {
    //            AuthInfo authinfo = new AuthInfo();
    //            authinfo.ID = profileDomain.ID;
    //            authinfo.Fullname = profileDomain.Fullname;
    //            authinfo.EmailAddress = profileDomain.EmailAddress;
    //            authinfo.GroupID = profileDomain.GroupID.ID;
    //            authinfo.BranchID = profileDomain.BranchID.ID;
    //            authinfo.HO = profileDomain.BranchID.HeadOffice;

    //            Collection<Dictionary<string, Dictionary<string, string>>> menu = new Collection<Dictionary<string, Dictionary<string, string>>>();
    //            GroupAuthorizationFacade authorizationFacade = new GroupAuthorizationFacade();
    //            menu = authorizationFacade.RetrieveMenuAuthorizationByGroupIDAndParentID(profileDomain.GroupID.ID, 0, "", new Collection<Dictionary<string, Dictionary<string, string>>>(), false);
    //            authinfo.MenuAuthorization = menu;

    //            JavaScriptSerializer serializer = new JavaScriptSerializer();
    //            string strAuth = serializer.Serialize(authinfo);
    //            FormsAuthentication.SetAuthCookie(strAuth, true);
    //        }
    //    }
    //    catch (Exception ex)
    //    {
    //        message = "Error: " + ex.Message.ToString();
    //        log.Debug("LoginBtn_Click() on Authentication.ascx.cs: " + ex.Message.ToString());
    //    }

    //    if (!string.IsNullOrEmpty(message)) Page.ClientScript.RegisterStartupScript(this.GetType(), "Warning!", "<script type='text/javascript'>UIBlock('" + message + "');</script>");
    //    else Response.Redirect("~/Main.aspx", false);
    //}

    protected void UserCurrent_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Account.aspx", false);
    }

    public void SignOutMethod()
    {
        //FormsAuthentication.SignOut();
        //Session.Abandon();

        //HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, "");
        //cookie.Expires = DateTime.Now.AddYears(-1);
        //Response.Cookies.Add(cookie);

        //cookie = new HttpCookie("ASP.NET_sessionId", "");
        //cookie.Expires = DateTime.Now.AddYears(-1);
        //Response.Cookies.Add(cookie);

        //FormsAuthentication.RedirectToLoginPage();

        string userLoggedIn = (Session["UserLoggedIn"] == null ? string.Empty : (string)Session["UserLoggedIn"]);

        if (userLoggedIn.Length > 0)
        {
            System.Collections.Generic.List<string> d = Application["UsersLoggedIn"] as System.Collections.Generic.List<string>;
            if (d != null)
            {
                lock (d)
                {
                    d.Remove(userLoggedIn);
                }
            }
        }

        FormsAuthentication.SignOut();
        Session.Abandon();

        HttpCookie aCookie;
        string cookieName;
        int limit = Request.Cookies.Count;
        for (int i = 0; i < limit; i++)
        {
            cookieName = Request.Cookies[i].Name;
            aCookie = new HttpCookie(cookieName);
            aCookie.Expires = DateTime.Now.AddDays(-1);
            Response.Cookies.Add(aCookie);
        }

        Response.Redirect(FormsAuthentication.LoginUrl, false);

    }

    public void SignOutTestMethod()
    {
        FormsAuthentication.SignOut();
        FormsAuthentication.RedirectToLoginPage();
    }

    protected void SignOut_Click(object sender, EventArgs e)
    {
        this.SignOutMethod();
    }

    //protected void StartPsycometry_Click(object sender, EventArgs e)
    //{
    //    string candidateid = CandidateID.Value;

    //    Candidate candidateDomain = new Candidate();
    //    CandidateFacade candidateFacade = new CandidateFacade();
    //    string message = string.Empty;

    //    try
    //    {
    //        candidateid = candidateid.Replace("FB", "").Replace("fb", "");
    //        int ID = Convert.ToInt32(candidateid.ToString());
    //        candidateDomain = candidateFacade.RetrieveCandidateByID(ID);

    //        if (candidateDomain.ID == 0)
    //        {
    //            message = "ID did not recognized!";
    //        }
    //        else
    //        {
    //            AuthInfo authinfo = new AuthInfo();
    //            authinfo.ID = candidateDomain.ID;
    //            authinfo.Fullname = candidateDomain.Fullname;
    //            authinfo.EmailAddress = candidateDomain.Email;
    //            authinfo.GroupID = 0;
    //            authinfo.BranchID = 0;
    //            authinfo.HO = false;

    //            Dictionary<string, Dictionary<string, string>> menu = new Dictionary<string, Dictionary<string, string>>();
    //            Collection<Dictionary<string, Dictionary<string, string>>> menuList = new Collection<Dictionary<string, Dictionary<string, string>>>();
    //            Dictionary<string, string> menuLevel1 = new Dictionary<string, string>();

    //            menuLevel1.Add("ID", "0");
    //            menuLevel1.Add("Parent", "Test");
    //            menuLevel1.Add("Title", "Psycometry Test");
    //            menuLevel1.Add("Url", "Test/Welcome.aspx");

    //            menu.Add("Menu", menuLevel1);
    //            menuList.Add(menu);
    //            authinfo.MenuAuthorization = menuList;

    //            JavaScriptSerializer serializer = new JavaScriptSerializer();
    //            string strAuth = serializer.Serialize(authinfo);
    //            FormsAuthentication.SetAuthCookie(strAuth, true);
    //        }
    //    }
    //    catch (Exception ex)
    //    {
    //        message = "Error: " + ex.Message.ToString();
    //        log.Debug("StartPsycometry_Click() on Authentication.ascx.cs: " + ex.Message.ToString());
    //    }

    //    if (!string.IsNullOrEmpty(message)) Page.ClientScript.RegisterStartupScript(this.GetType(), "Warning!", "<script type='text/javascript'>UIBlock('" + message + "');</script>");
    //    else Response.Redirect("~/Test/Welcome.aspx", false);
    //}

}